package club.zbiao.modules.system.service.impl;

import club.zbiao.modules.system.domain.BaseEntity;
import club.zbiao.modules.system.repo.BaseRepository;
import club.zbiao.modules.system.service.BaseService;
import club.zbiao.modules.system.service.dto.BaseDTO;
import club.zbiao.modules.system.service.mapper.BaseMapper;
import club.zbiao.utils.ValidationUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.Optional;

/**
 * @author zbiao
 * @date 2019-05-22
 */
public class BaseServiceImpl<D extends BaseDTO, E extends BaseEntity, M extends BaseMapper<D, E>, R extends BaseRepository<E>> implements BaseService<D, E> {

    @Autowired
    protected R repo;

    @Autowired
    protected M mapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public D create(E resources) {
        return mapper.toDto(repo.save(resources));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(E resources) {
        Optional<E> optionalDict = repo.findById(resources.getId());
        ValidationUtil.isNull(optionalDict, "E", "id", resources.getId());

        E dict = optionalDict.get();
        // 此处需自己修改
        resources.setId(dict.getId());
        repo.save(resources);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void delete(Long id) {
        repo.deleteById(id);
    }
}